package com.example.base.utils;

import java.time.Duration;
import java.util.Date;

public class TimeUtils {

    public static String dateFormatAgo( Date createTime){
        // 计算创建时间距离当前时间的时长
        Date currentTime = new Date();
        long durationMillis = currentTime.getTime() - createTime.getTime();
        Duration duration = Duration.ofMillis(durationMillis);
        // 将时长转换成“几分钟前”，“几小时前”，“多少天前”，“多少年前”等形式
        if (duration.toMinutes() < 60) {
            return duration.toMinutes() + "分钟前";
        } else if (duration.toHours() < 24) {
            return duration.toHours() + "小时前";
        } else if (duration.toDays() < 365) {
            return duration.toDays() + "天前";
        } else {
            long years = duration.toDays() / 365;
            return years + "年前";
        }
    }
}
